package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by 甘静斌 on 2020-08-17 23:03
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStrategyVORedisService strategyVORedisService;
    //当spring容器启动并初始化之后马上执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        System.out.println("-----------初始化vo对象--starts---------");
        //查询mongodb所有攻略
        List<Strategy> list = strategyService.list();
        //遍历所有攻略,封装成vo对象
        for (Strategy strategy : list) {
            /**
             * 如果第一次初始化后,前端进行vo对象统计,redis中统计数据跟数据库中数据不一致了
             * 如果第二次再进行初始化,后面操作会覆盖之前redis缓存的vo对象.
             *
             * 如果vo已经存在了 , 直接跳过 , 不需要初始化
             *
             */
            if (strategyVORedisService.isStrategyVoExist(strategy.getId())) {
                continue;
            }

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo );
            vo.setStrategyId(strategy.getId());
            strategyVORedisService.setStatisVo(vo);
        }

        //将vo缓存到redis中
        System.out.println("-----------初始化vo对象--end---------");
    }
}
